/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.cam.ccn.sac.modules.publicmessage;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import uk.ac.cam.ccn.sac.net.CCNNet;
import uk.ac.cam.ccn.sac.net.CCNNet.TextCallBack;

/**
 *
 * @author Thomas
 */
public class TextElement extends JFrame implements ActionListener, TextCallBack{
    private JTextArea  messages = new JTextArea(32, 32);
    private JTextField input   = new JTextField(32);
    
    public TextElement(){
        super("Chat");
        this.setSize(200, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container content = getContentPane();
        messages.setEditable(false);
        messages.setLineWrap(true);
        // insert the messages gui element within a scroll area
        content.add(new JScrollPane(messages), BorderLayout.CENTER);
        
        input.addActionListener(this);
        content.add(input, BorderLayout.SOUTH);        
        pack();
        input.requestFocusInWindow();
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try{
            String toBeSent = input.getText();

            if(toBeSent!=null && toBeSent.length() > 0){
                if(toBeSent.charAt(0)=='@'){
                    String[] splits = toBeSent.split(" ", 2);
                    // it should be two!
                    if(splits.length==2){
                        // remove the @
                        String to = splits[0].replaceAll("@", "");
                        String msg = splits[1];
                        CCNNet.getInstance().sendPrivateText(to, msg);
                    }
                }else{
                    CCNNet.getInstance().sendText(toBeSent);
                }
            }
        }catch(Exception ex){
            System.out.println(ex.getMessage());
            messages.insert("Exception : "+ex.getMessage()+"\n", messages.getText().length());
            messages.setCaretPosition(messages.getText().length());
        }
        input.setText("");
        input.requestFocusInWindow();
    }

    @Override
    public void textReceived(String message) {
        messages.insert(message+"\n", messages.getText().length());
        messages.setCaretPosition(messages.getText().length());
    }
}
